import React, { useEffect, useState } from 'react';
import { Table, Input, 
  InputNumber, Popconfirm, 
  Form, Typography,
  Modal,Button, message,Spin, Space,Upload, Tag,Select 
} from 'antd';
import { LoadingOutlined, PlusOutlined  } from '@ant-design/icons';
import {userList,userUpdate,userDelete,userInputAdd} from '@/services/user-list/userListApi'
import {integralList} from '@/services/integral-list/integral'
import { userLogins } from '@/services/user-login/userLogin';
import styles from './UserTableList.less';
import { isNull } from 'lodash';
import Item from 'antd/lib/list/Item';
import ImgCrop from 'antd-img-crop';
import moment from 'moment';
import {PORT} from '@/services/requestPath/index'
const { Option } = Select;
const qnup = PORT+"/uploadPictures"

interface Item {
  id: number;
  userName: string;
  passWord: string;
  zgEmail: string;
  telephone: string;
  address: string;
  createTime?:string;
  updateTime?:string;
  headerImg:string;
}

interface ImageItem{
  uid:string;
  name:string;
  status:string;
  url:string;
}

//兑换记录response 
interface ExchangerecordResponseVo{
    id?: number;
    createTime?: string;
    updateTime?: string;
    dFlag?: any;
    couponTitle?: string;
    discountHowMuch?: any;
    couponCount?: number;
    zgUserId?: number;
    couponState?: number;
    userName?:string;
    zgEmail?:string;
  }

interface CouponResponseVo{
    id?: number;
    createTime?: string;
    updateTime?: string;
    dFlag?: any;
    couponTitle?: string;
    discountHowMuch?: any;
    couponCount?: number;
    zgUserId?: number;
    couponState?: number;
}  

interface OrderInsIntegralVo{
    id?:number;
    orderNo?:string;
    createTime?:string;
    updateTime?:string;
    addIntegral?:number;
    orderImages?:string;
    zgUserId?:number;
    page?:number;
    limit?:number;
    userName?:string;
    zgEmail?:string;
  }

const Index = () => {

  const [form] = Form.useForm();
  const [data, setData] = useState<Item[]>([]);
  const [editingKey, setEditingKey] = useState(0);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [user,setTableUser] = useState<Item>({});
  const [userNull,setUserNull] = useState<Item>({})
  const [userName,setUserName] = useState<string>("")
  const [passWord,setPassWord] = useState<string>("")
  const [zgEmail,setEmail] = useState<string>("")
  const [telephone,setTelephone] = useState<string>("")
  const [address,setAddress] = useState<string>("")
  const [searchInput,setSearchInput] = useState("")
  const [fileList, setFileList] = useState([]);
  const [header,setHeader] = useState("")
  const [page,setPage] = useState(1)
  const [limit,setLimit] = useState(10)
  const [total,setTotal] = useState(0);
  const [exchange,setExchangeRecordList] = useState<OrderInsIntegralVo[]>([])
  const [valueChange,setHandleChange] = useState<number>()
  useEffect(()=>{
    async function userLists(){
      const params = {
        page:page,
        limit:limit,
      }
      const users = await integralList(params);
      await setExchangeRecordList(users.list)
      console.log(users)
      await setTotal(users.total)
      await setData(users.list)
      await setTableUser(userNull)
     
    }
    userLists()
    console.log(userNull)
    setSearchInput("")
  },[])


  const onChange = ({ fileList: newFileList}) => {
    //newFileList[0].response = 
    console.log(newFileList)
    //debugger
    setFileList(newFileList);
    console.log(newFileList)
    console.log(fileList)
    //debugger
    if(newFileList.length>=1){

      // server data splic + QN + newFileList[0].response
      setHeader(newFileList[0].response)
    }else{
      setHeader("")
    }

    //get data response list   
    //console.log(newFileList[0].response)
    console.log(newFileList)
    console.log(fileList)
  };

  const handleChange=async(value:any)=> {

    await setHandleChange(parseInt(value))

    let formInpu = {
      orderStart:parseInt(value),
      userName:searchInput.replaceAll(" ",""),
      page:page,
      limit:limit
    }

    //debugger
    if(parseInt(value) === 1 || parseInt(value) === 2){
      const users = await integralList(formInpu);
      await setExchangeRecordList(users.list)
      await setTotal(users.total)
    }else{
      const users = await integralList({page:page,limit:limit});
      await setExchangeRecordList(users.list)
      await setTotal(users.total)
    }

  }
    

  //click image 
  const onPreview = async (file:any) => {
    let src = file.url;
    if (!src) {
      src = await new Promise(resolve => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj);
        reader.onload = () => resolve(reader.result);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow.document.write(image.outerHTML);
  };

  //model data
  const showModal =async (e:Item) => {
      //修改折扣吗
    // setIsModalVisible(true);
    // console.log(e)
    // //debugger
    // if(e.id){
    //   setTableUser(e)
    //   setUserName(e.userName)
    //   setPassWord(e.passWord)
    //   setEmail(e.zgEmail)
    //   setTelephone(e.telephone)
    //   setAddress(e.address)
    //   setHeader(e.headerImg)
    //   if(e.headerImg){
    //     setFileList<ImageItem>([{
    //       uid: '-1',
    //       name: 'image.png',
    //       status: 'done',
    //       url:e.headerImg,
    //      }])
    //   }
    // }else{
    //   setUserName("")
    //   setPassWord("")
    //   setEmail("")
    //   setTelephone("")
    //   setAddress("")
    //   setHeader("")
    //   setTableUser(userNull)
    // }
  };

  const handleOk =async () => {

    //get imagelist post request
    //const imgResponse = await reqeustImage();


    //stop modal request
    setIsModalVisible(false);

    let formInpu = {
      id:user.id,
      userName:userName,
      passWord:passWord,
      zgEmail:zgEmail,
      telephone:telephone,
      address:address,
      headerImg:header.length > 2?"http://"+header:""
    }

    if(!user.id){
      let formInputAdd = {
        userName:userName,
        passWord:passWord,
        zgEmail:zgEmail,
        telephone:telephone,
        address:address,
        headerImg:header.length > 2?"http://"+header:""
      }
      await userInputAdd(formInputAdd)
    }else{
      await userUpdate(
        formInpu
       );
    }
   
   const users = await userList({page:page,limit:limit});
    await setData(users.list)
    await setFileList([])
    
  };

  const handleCancel= async ()=>{

    //await setTableUser(userNull)
    await setIsModalVisible(false);

    await setTableUser(userNull)

    await setFileList([])

 
  }

  const searchOnClick = async()=>{
    
    console.log(searchInput)
    
    let formInpu = {
      userName:searchInput.replaceAll(" ",""),
      page:page,
      limit:limit,
      orderStart:valueChange
    }

    console.log(formInpu)

    if(formInpu.userName || formInpu.orderStart){
      const users = await integralList(formInpu);
      await setExchangeRecordList(users.list)
      await setTotal(users.total)
    }else{
      const users = await integralList({page:page,limit:limit});
      await setExchangeRecordList(users.list)
      await setTotal(users.total)
    }

  }

  const cancel = async()=>{
    await setTableUser(userNull)
    await setFileList([])
  }

  const deleteModel= async (e:Item)=>{
    console.log(e.id)

    // const deleteResponse = await userDelete(e.id);
    // console.log(deleteResponse)
    // if(deleteResponse === 1){
    //   const userListResponse = await userList({page:page,limit:limit});
    //   await setData(userListResponse.list);
    //   await setTotal(userListResponse.total)
    // }
    
  }

  const onShowSizeChange =async(e:any)=>{
    // current : 1 2 3
    // defaultCurrent:1  
    // pageSize: 10
    console.log(e)
    setPage(parseInt(e.current))
    const param = {
      userName:searchInput.replaceAll(" ",""),
      orderStart:valueChange,
      page:parseInt(e.current),
      limit:limit
    }

    console.log("请求参数打印.......")
    console.log(param.userName)
    console.log(param)
    
    const responseUsers = await integralList(param); 
    setExchangeRecordList(responseUsers.list)
  }

  const isEditing = (record: Item) => record.id === editingKey;

  const save = async (key: React.Key) => {
    try {
      const row = (await form.validateFields()) as Item;
      const newData = [...data];
      const index = newData.findIndex(item => key === item.id); // item.key
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        setData(newData);
        setEditingKey(0);
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey(0);
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      width: '10%',
      editable: true,
    },
    {
      title: '用户名',
      dataIndex: 'userName',
      width: '10%',
      editable: true,
    },
    {
        title: '邮箱',
        dataIndex: 'zgEmail',
        width: '15%',
        editable: true,
      },
    {
        title: '订单号',
        dataIndex: 'orderNo',
        width: '22%',
        editable: true,
        render:orderNo => <span>{orderNo}</span>
      },
    {
      title: '积分',
      dataIndex: 'integralCount',
      width: '10%',
      editable: true,
      render:integralCount => <span>{parseInt(integralCount)}积分</span>
    },
    {
        title: '使用记录',
        dataIndex: 'orderStart',
        width: '10%',
        editable: true,
        render:orderStart => <>{orderStart===1?<span style={{color:"red"}}>增加了</span>:<span style={{color:"#ccc"}}>消费了</span> }</>
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: '10%',
      editable: true,
      render:createTime => <span>{moment(new Date(parseInt(createTime))).format("YYYY-MM-DD")}</span>
    },

    {
      title: '操作',
      dataIndex: 'operation',
      render: (_: any, record: Item) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <a href="javascript:;" onClick={() => save(record.id)} style={{ marginRight: 8 }}>
              Save
            </a>
            <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
              <a>Cancel</a>
            </Popconfirm>
          </span>
        ) : (
         <div>
            <Typography.Link disabled={editingKey !== 0} onClick={()=>showModal(record)}>
              <Button type="primary">修改</Button>
            </Typography.Link>
            <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
            <Typography.Link disabled={editingKey !== 0} 
            >
              <Popconfirm title="真的要删除吗？" cancelText="不不不"  okText="是的" onConfirm={()=>deleteModel(record)}>
                <a href="#">Delete</a>
              </Popconfirm>
            </Typography.Link>
         </div>
        );
      },
    },
  ];

  return (
   <div>
     {/* search */}
      <div style={{display:"flex",flexDirection:"row",justifyContent:"space-between"}}>
      <div style={{display:"flex",flexDirection:"row",justifyContent:"flex-start"}}><Input placeholder="请输入您要搜索的内容!" 
      maxLength={50} onChange={txt=>setSearchInput(txt.target.value)} 
      value={searchInput} allowClear></Input><Button type="primary" onClick={searchOnClick}>搜索</Button><Select defaultValue="2" style={{ width: 120 }} onChange={handleChange}>
      <Option value="1">增加的</Option>
      <Option value="2">消费的</Option>
      <Option value="3">所有的</Option>
    </Select></div>
      <div><Button type="primary" onClick={()=>showModal(user)}>新增</Button></div>
      </div>

    <Modal 
    centered
    title={user.id?"修改":"新增"} visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}
    width={1000}
    >
    <p>用户名:<Input type="text" placeholder="请输入用户名" value={userName} 
    onChange={txt=>setUserName(txt.target.value)}></Input></p>
    <p>地址:<Input type="text" placeholder="请输入地址" value={address} 
    onChange={txt=>setAddress(txt.target.value)}
    ></Input></p>
    <p>手机号:<Input type="text" placeholder="请输入手机号" value={telephone}
    onChange={txt=>setTelephone(txt.target.value)}
     ></Input></p>
    <p>邮箱:<Input type="text" placeholder="请输入邮箱" value={zgEmail}
    onChange={txt=>setEmail(txt.target.value)}
     ></Input></p>
    <p>密码:<Input type="text" placeholder="请输入密码" value={passWord} 
    onChange={txt=>setPassWord(txt.target.value)}
    ></Input></p>
      <>
        <ImgCrop rotate>
          <Upload
            action={qnup}
            listType="picture-card"
            fileList={fileList}
            onChange={onChange}
            onPreview={onPreview}
            headers={{
              "Authorization":`${localStorage.getItem("token")}`,
              "TimeSystemCurrent":`${new Date().getTime()}`
            }}
          >
            {fileList.length < 1 && '+ Upload'}
          </Upload>
        </ImgCrop>
      </>
    </Modal>
    <Table 
    bordered
    columns={columns} 
    dataSource={exchange}
    pagination={{
      onChange: cancel,
      defaultCurrent:1,
      pageSize:limit,
      total:total
      //onShowSizeChange:{onShowSizeChange}
    }}
    onChange={onShowSizeChange}
     />   
   </div>
  );
};

export default Index;
